package com.easylinkin.linkappapi.roster.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.easylinkin.linkappapi.common.model.RequestModel;
import com.easylinkin.linkappapi.roster.dto.LaborTeamDTO;
import com.easylinkin.linkappapi.roster.entity.LaborTeam;
import com.easylinkin.linkappapi.roster.service.ILaborTeamService;
import com.easylinkin.linkappapi.security.context.LinkappUserContextProducer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import site.morn.rest.RestBuilders;
import site.morn.rest.RestMessage;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 人员管理/劳务队伍管理
 */
@RestController
@RequestMapping("/laborTeam")
public class LaborTeamController {

    @Autowired
    private ILaborTeamService laborTeamService;

    @Autowired
    private LinkappUserContextProducer linkappUserContextProducer;

    /**
     * 分页查询
     */
    @PostMapping("/getPage")
    public RestMessage getPage(@RequestBody RequestModel<LaborTeamDTO> requestModel) {
        // 自动带入tenantId
        String tenantId = linkappUserContextProducer.getNotNullCurrent().getTenantId();
        if (requestModel.getCustomQueryParams() == null) {
            requestModel.setCustomQueryParams(new LaborTeamDTO());
        }
        requestModel.getCustomQueryParams().setTenantId(tenantId);
        IPage<LaborTeam> page = laborTeamService.selectPage(requestModel.getPage(), requestModel.getCustomQueryParams());
        return RestBuilders.successBuilder(page).build();
    }

    /**
     * 新增
     */
    @PostMapping("/save")
    public RestMessage save(@RequestBody LaborTeamDTO dto) {
        boolean result = laborTeamService.saveLaborTeam(dto);
        return result ? RestBuilders.successBuilder().message("新增成功").build()
                      : RestBuilders.failureBuilder().message("新增失败").build();
    }

    /**
     * 编辑
     */
    @PostMapping("/edit")
    public RestMessage edit(@RequestBody LaborTeamDTO dto) {
        boolean result = laborTeamService.updateLaborTeam(dto);
        return result ? RestBuilders.successBuilder().message("编辑成功").build()
                      : RestBuilders.failureBuilder().message("编辑失败").build();
    }

    /**
     * 删除
     */
    @DeleteMapping("/del")
    public RestMessage del(String ids) {
        Map<String, String> stringStringMap = laborTeamService.deleteLaborTeam(ids);
        return stringStringMap.isEmpty() ? RestBuilders.successBuilder().message("删除成功").build()
                //如果删除失败，返回错误信息
                      : RestBuilders.failureBuilder().message(stringStringMap.values().stream().collect(Collectors.joining(";"))).build();
    }
} 